package com.zsh.wanandroid.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author zsh
 * @date 2019/12/13.
 * 功能：
 */

public class ViewHolder {

    private SparseArray<View> mViews;//存放view
    private int mPosition;//Item的position
    private View mConvertview;//加载的视图View

    /**
     * 构造方法中对数据进行初始化并加载视图View，以及将ViewHolder实例设置成convertView的tag
     *
     * @param context
     * @param parent
     * @param layoutId
     * @param position
     * @param mInflater
     */
    public ViewHolder(Context context, ViewGroup parent, int layoutId, int position, LayoutInflater mInflater) {
        this.mViews = new SparseArray<View>();
        this.mPosition = position;
        this.mConvertview = mInflater.inflate(layoutId, parent, false);
        mConvertview.setTag(this);
    }

    /**
     * 获取ViewHolder实例
     *
     * @param context
     * @param convertview
     * @param parent
     * @param layoutId
     * @param position
     * @param mInflater
     * @return
     */
    public static ViewHolder get(Context context, View convertview, ViewGroup parent, int layoutId, int position, LayoutInflater mInflater) {

        if (convertview == null) {
            return new ViewHolder(context, parent, layoutId, position, mInflater);
        } else {
            ViewHolder holder = (ViewHolder) convertview.getTag();
            holder.mPosition = position;
            return holder;
        }

    }

    /**
     * 通过viewId获取控件
     *
     * @param resId
     * @return
     */
    public <T extends View> T getView(int resId) {

        View view = mViews.get(resId);
        if (view == null) {
            view = mConvertview.findViewById(resId);
            mViews.put(resId, view);
        }
        return (T) view;
    }


    public View getmConvertView() {
        return mConvertview;
    }

    /**
     * 设置TextView显示文本
     *
     * @param resId
     * @param str
     * @return
     */
    public ViewHolder setText(int resId, String str) {
        TextView tv = (TextView) this.getView(resId);
        tv.setText(str);
        return this;
    }

    /**
     * 设置ImageView显示
     */
    public ViewHolder setImageResources(int resId, int rid) {
        ImageView iv = (ImageView) this.getView(resId);
        iv.setImageResource(rid);
        return this;
    }

    /**
     * 设置ImageView显示成Bitmap
     *
     * @param resId
     * @param bm
     * @return
     */
    public ViewHolder setImageBitmap(int resId, Bitmap bm) {
        ImageView iv = (ImageView) this.getView(resId);
        iv.setImageBitmap(bm);
        return this;
    }

}
